package com.fancyy.scm.util;

import android.content.Context;
import android.media.AudioManager;
import android.media.SoundPool;

import java.util.HashMap;
import java.util.Map;

/**
 * Created by jingr on 2018/3/25.
 */

public class SoundUtils {
    private Map<Integer, Integer> tunesSoundMap = new HashMap<Integer, Integer>();
    private SoundPool soundPool;

    private static SoundUtils _soundUtils;
    public static SoundUtils ShareManager()
    {
        if(_soundUtils == null)
        {
            _soundUtils = new SoundUtils();
        }
        return _soundUtils;
    }

    public SoundUtils()
    {
        soundPool = new SoundPool(5, AudioManager.STREAM_MUSIC, 0);
    }

    public void PlaySound(Context context, int soundRaw)
    {
        if(!tunesSoundMap.isEmpty() && tunesSoundMap.containsKey(soundRaw))
        {
            soundPool.play(tunesSoundMap.get(soundRaw), 1, 1, 0, 0, 1);
        }
        else
        {
            final int soundResource = soundPool.load(context, soundRaw, 1);
            tunesSoundMap.put(soundRaw, soundResource);

            //等待资源加载完成
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            soundPool.play(soundResource, 1, 1, 0, 0, 1);
        }
    }

    public int PlayLoopSound(Context context, int soundRaw)
    {
        if(!tunesSoundMap.isEmpty() && tunesSoundMap.containsKey(soundRaw))
        {
           return soundPool.play(tunesSoundMap.get(soundRaw), 1, 1, 0, -1, 1);
        }
        else
        {
            final int soundResource = soundPool.load(context, soundRaw, 1);
            tunesSoundMap.put(soundRaw, soundResource);

            //等待资源加载完成
            try {
                Thread.sleep(200);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            return soundPool.play(soundResource, 1, 1, 0, -1, 1);
        }
    }

    public void StopSound(int streamID)
    {
        soundPool.stop(streamID);
    }
}
